#include<vector>
#include<queue>
using namespace std;

class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};


class Solution {
public:
    Node* connect(Node* root) {
        if (root == NULL) return root;
        queue<Node*> queue_;
        queue_.push(root);
        while (!queue_.empty()) {
            int size = queue_.size();
            while (size-- > 0) {
                Node* node = queue_.front();
                queue_.pop();
                node->next = size == 0 ? NULL : queue_.front();
                if (node->left != NULL) queue_.push(node->left);
                if (node->right != NULL) queue_.push(node->right);
            }
        }
        return root;
    }
};